package com.milk.nettylearn.nio;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static com.milk.nettylearn.nio.ByteBufferUtil.debugAll;

public class TestByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("Hello,world\nI'm zhangsan\nHo");
//        debugAll(buffer1);
//        ByteBuffer buffer1 = ByteBuffer.allocate(27);
//        buffer1.put("Hello,world\nI'm zhangsan\nHo".getBytes());
//        debugAll(buffer1);
        split(buffer1);
//        debugAll(buffer1);
        buffer1.put(StandardCharsets.UTF_8.encode("w are you?\n"));
        buffer1.flip();
        split(buffer1);
//        buffer1.put("w are you?\n".getBytes());
////        debugAll(buffer1);
//        split(buffer1);
//        debugAll(buffer1);
    }

    private static void split(ByteBuffer source) {
//        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer buffer = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    buffer.put(source.get());
                }
                debugAll(buffer);
            }
        }
        source.compact();
    }


}
